package basic;

import java.util.Objects;

/**
 * @Description: TODO 重写equals
 * @Author: wzj
 * @Date: 2020/11/20 14:54
 */
public class RewriteEquals {
    public static void main(String[] args) {
        ParentClass parentClass=new ParentClass("test1");
        ParentClass parentSonClass=new SonClass("test1");
        System.out.println(parentClass.equals(parentSonClass));
    }
}

class ParentClass{
    String name;

    public ParentClass() {
    }

    public ParentClass(String name) {
        this.name = name;
    }

    /**
     * 第一种情况
     * @param o 这里的o必须是ParentClass对象 否则为false
     * @return
     */
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ParentClass that = (ParentClass) o;
        return Objects.equals(name, that.name);
    }

    /**
     * 第二种情况
     * @param o 如果o是ParentClass的子类对象这里也可以使equals相等
     * @return
     */
    /*@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof ParentClass)) return false;//这一行和上面的equals不一样
        ParentClass that = (ParentClass) o;
        return Objects.equals(name, that.name);//如果要返回true，子类需要把ParentClass的name赋上值
    }*/

    @Override
    public int hashCode() {

        return Objects.hash(name);
    }
}

class SonClass extends ParentClass{
    String name;//1

    public SonClass(String name) {
//        super(name);
        this.name = name;
    }
}